package com.bicon.botu.account.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.account.common.AccountConstants;
import com.bicon.botu.account.dto.RoleDto;
import com.bicon.botu.account.entity.AccountRole;
import com.bicon.botu.account.entity.Role;
import com.bicon.botu.account.handler.AccountHandler;
import com.bicon.botu.account.mapper.AccountRoleMapper;
import com.bicon.botu.account.service.IAccountRoleService;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @auther 裴志鹏
 * @date 2017/11/30 10:42
 */
@Slf4j
@Service
public class AccountRoleServiceImpl extends ServiceImpl<AccountRoleMapper, AccountRole> implements IAccountRoleService {

    @Autowired
    private RedisHandler redisHandler;

    @Autowired
    private AccountRoleMapper accountRoleMapper;


    @Autowired
    private AccountHandler accountHandler;

    /**
     * 增加账号角色关联
     *
     * @param accountId 账号id
     * @param roleIds   角色Id,可多个一起传。英文逗号隔开“,”
     * @param type      账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult saveAccountRoleIds(String accountId, String[] roleIds, String type) {
        List<AccountRole> accountRoleList = new ArrayList<>();
        for (String roleId : roleIds) {
            AccountRole accountRole = new AccountRole();
            accountRole.preInsert();
            accountRole.setAccountId(accountId);
            accountRole.setRoleId(roleId);
            accountRole.setType(type);
            accountRole.setLogicDelete(Constants.DEL_LOGIC_NORMAL);
            accountRoleList.add(accountRole);
        }
        insertBatch(accountRoleList);
//      添加redis缓存
        if ("0".equals(type)) {
            List<String> roleList = new ArrayList<>();
            for (String roleId : roleIds) {
                roleList.add(roleId);
            }
            if (redisHandler.getGlobalRedisTemplate().hasKey(AccountConstants.ACCOUNT_ROLE + accountId)) {
                List<String> list = redisHandler.getGlobalRedisTemplate().getList(AccountConstants.ACCOUNT_ROLE, accountId);
                redisHandler.getGlobalRedisTemplate().remove(AccountConstants.ACCOUNT_ROLE, accountId);
                list.addAll(roleList);
//              对list去重
                HashSet hashSet = new HashSet(list);
                list.clear();
                list.addAll(hashSet);
                redisHandler.getGlobalRedisTemplate().cacheList(AccountConstants.ACCOUNT_ROLE, accountId, list);
            } else {
                redisHandler.getGlobalRedisTemplate().cacheList(AccountConstants.ACCOUNT_ROLE, accountId, roleList);
            }
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 删除账号角色关联
     *
     * @param accountId 账号id
     * @param type      账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public BaseResult deleteAccountRoleByAccountId(String accountId, String type) {
        AccountRole accountRole = new AccountRole();
        accountRole.setLogicDelete(Constants.DEL_LOGIC_DELETE);
        accountRole.preUpdate();
        boolean result = accountRole.update(new EntityWrapper<AccountRole>().eq("account_id", accountId).eq("type", type));
        if (result) {
//          移除redis缓存
            if ("0".equals(type)) {
                redisHandler.getGlobalRedisTemplate().remove(AccountConstants.ACCOUNT_ROLE, accountId);
            }
            log.info("delete AccountRole success");
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        } else {
            log.info("delete AccountRole fail");
            return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
        }
    }

    /**
     * 查询当前账号下的角色
     *
     * @param accountId 账号Id
     * @param type      账户类型：0：前台账户，1：后台账户
     * @return
     */
    @Override
    public List<RoleDto> selectRolesByAccountId(String accountId, String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        map.put("type", type);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        List<RoleDto> roles = accountRoleMapper.getRoleByAccountId(map);
        return roles;
    }

    /**
     * 添加账户角色
     *
     * @param accountId 账户id
     * @param code      角色code
     * @return
     */
    @Override
    public BaseResult addAccountRole(String accountId, String code) {
        //      查询code对应的角色
        Role role = new Role().selectOne(new EntityWrapper<Role>().eq("code", code).eq("type", "0").eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (role == null) {
            return new BaseResult(Constants.RESPONSE_CODE_602, "code：" + code + "，不存在，请先增加code对应的角色");
        }
        AccountRole accountRole = new AccountRole();
        accountRole.preInsert();
        accountRole.setAccountId(accountId);
        accountRole.setType("0");
        accountRole.setRoleId(role.getId());
        boolean result = accountRole.insert();
        if (result) {
            accountHandler.initAccountRole(accountId);
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        }
        return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
    }

    /**
     * 删除账号角色关联
     *
     * @param accountId 账号id
     * @param type      账户类型：0：前台账户，1：后台账户
     * @param code      角色code
     * @return
     */
    @Override
    public BaseResult deleteAccountRole(String accountId, String type, String code) {
        //      查询code对应的角色
        Role role = new Role().selectOne(new EntityWrapper<Role>().eq("code", code).eq("type", "0").eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (role == null) {
            return new BaseResult(Constants.RESPONSE_CODE_602, "code：" + code + "，不存在，请先增加code对应的角色");
        }
        AccountRole accountRole = new AccountRole();
        accountRole.preUpdate();
        accountRole.setLogicDelete(Constants.DEL_LOGIC_DELETE);
        boolean result = accountRole.update(new EntityWrapper<AccountRole>().eq("account_id", accountId).eq("role_id", role.getId()).eq("type", type));
        if (result) {
            accountHandler.initAccountRole(accountId);
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        }
        return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
    }
}
